/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.hisense.settings;

import android.app.Dialog;
import android.app.Activity;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import com.android.settings.R;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.text.format.DateFormat;
import android.widget.DatePicker;
import android.widget.TimePicker;
import android.util.Log;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

import com.hisense.settings.util.Wrapper;

import android.content.ContentResolver;
import android.preference.PreferenceManager; 

public class PowerOnTimer  extends PreferenceActivity 
        implements Preference.OnPreferenceChangeListener{

	final static String M12 = "h:mm aa";
    final static String M24 = "kk:mm";
	final static String AUTO_ON_FLAG = "auto_on_flag";
	final static String AUTO_ON_HOUR = "auto_on_hour";
	final static String AUTO_ON_MINUTE = "auto_on_minute";
	final static String AUTO_OFF_FLAG = "auto_off_flag";
	final static String AUTO_OFF_HOUR = "auto_off_hour";
	final static String AUTO_OFF_MINUTE = "auto_off_minute";
		
	private boolean bAutoOnEnabled;
	private boolean bAutoOffEnabled;
	private int mAutoOnHour =0;
	private int mAutoOnMinute =0;
	private int mAutoOffHour =0;
	private int mAutoOffMinute =0;

    private Preference mCurrentTimeShowPref;
    private Preference mSetPowerOntimer;
    private CheckBoxPreference mAutoOnEnabledPref;
    private Preference mAutoOnTimePref;
	private CheckBoxPreference mAutoOffEnabledPref;
    private Preference mAutoOffTimePref;
    private Activity mActivity;
    private ContentResolver mContentResolver; 
    private static long poweron_time = 0;    
    private static long currenttime;
    private static long setontime[] = new long[8];
    public  long time;
    private Wrapper mwrapper=null;
    
    SharedPreferences.Editor editor;
    
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        //mActivity = getActivity();
        //mContentResolver = mActivity.getContentResolver(); 
        addPreferencesFromResource(R.xml.power_on_timer);  
		mSetPowerOntimer =  findPreference("set_power_on_time");
		mSetPowerOntimer.setOnPreferenceChangeListener(this);


		
		
       // initUI();        
		mCurrentTimeShowPref = findPreference("current_time_show");
        java.text.DateFormat shortDateFormat = DateFormat.getDateFormat(this);
        Date now = Calendar.getInstance().getTime();
        mCurrentTimeShowPref.setTitle(shortDateFormat.format(now)+" "+DateFormat.getTimeFormat(this).format(now));
    }

/**    
    public void initUI() {
       mAutoOnEnabledPref = (CheckBoxPreference)findPreference("auto_on");
	   mAutoOnTimePref =  findPreference("auto_on_time");
	   mAutoOffEnabledPref = (CheckBoxPreference)findPreference("auto_off");
	   mAutoOffTimePref =  findPreference("auto_off_time");
	   mAutoOnEnabledPref.setOnPreferenceChangeListener(this);
	   mAutoOnTimePref.setOnPreferenceChangeListener(this);
	   mAutoOffEnabledPref.setOnPreferenceChangeListener(this);
	   mAutoOffTimePref.setOnPreferenceChangeListener(this);	  
    }
**/
    @Override
    public void onResume() {
       super.onResume();
       SharedPreferences mPowerOfftimer = PreferenceManager.getDefaultSharedPreferences(this);
       Boolean use_on_time=mPowerOfftimer.getBoolean("use_on_time",false);
	   
		int PowerOnhour_summary=mPowerOfftimer.getInt("poweron_hour", 12);
		int PowerOnminute_summary=mPowerOfftimer.getInt("poweron_minute", 0);
		mSetPowerOntimer.setSummary(PowerOnhour_summary+","+PowerOnminute_summary);
		
		Log.i("poweron_time",PowerOnhour_summary+","+PowerOnminute_summary+"&&&&&&&&&&");
		
       if(use_on_time==false){
    	   mSetPowerOntimer.setEnabled(false);
       }
       else
       {
    	   mSetPowerOntimer.setEnabled(true);	
       }
/*
	   if(1 == Settings.System.getInt(mContentResolver, AUTO_ON_FLAG, 0)) {
          bAutoOnEnabled  = true;
	   } else {
	 	  bAutoOnEnabled  = false;
	   }
	   mAutoOnEnabledPref.setChecked(bAutoOnEnabled);

	   if(1 == Settings.System.getInt(mContentResolver, AUTO_OFF_FLAG, 0)){
		  bAutoOffEnabled = true;
	   } else {
		 bAutoOffEnabled = false;
	   }

	   mAutoOffEnabledPref.setChecked(bAutoOffEnabled);
	   mAutoOnHour = Settings.System.getInt(mContentResolver, AUTO_ON_HOUR,0);		 
	   mAutoOnMinute = Settings.System.getInt(mContentResolver, AUTO_ON_MINUTE,0);
	   mAutoOnTimePref.setSummary(formatTime(mAutoOnHour,mAutoOnMinute));
	   mAutoOffHour = Settings.System.getInt(mContentResolver, AUTO_OFF_HOUR,0);
	   mAutoOffMinute = Settings.System.getInt(mContentResolver, AUTO_OFF_MINUTE,0);
       mAutoOffTimePref.setSummary(formatTime(mAutoOffHour,mAutoOffMinute));
	   mAutoOnTimePref.setEnabled(bAutoOnEnabled);
	   mAutoOffTimePref.setEnabled(bAutoOffEnabled);
*/
    }

    @Override 
    public void onPause() {
        super.onPause();    
    }
     
    @Override
    public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
       if (preference == mSetPowerOntimer){
		  showTimePicker(true);
        }
        return false;
    }

	public boolean onPreferenceChange(final Preference p, Object newValue) {
/*
		if(p == mAutoOnEnabledPref){
			bAutoOnEnabled = !bAutoOnEnabled;
			Settings.System.putInt(mContentResolver, AUTO_ON_FLAG, 
                                bAutoOnEnabled ? 1 : 0);
			SendAutoOnOffSetIntent();
			mAutoOnTimePref.setEnabled(bAutoOnEnabled);

		}else if(p == mAutoOffEnabledPref){
			bAutoOffEnabled = !bAutoOffEnabled;
			Settings.System.putInt(mContentResolver, AUTO_OFF_FLAG, 
                                bAutoOffEnabled ? 1 : 0);
			SendAutoOnOffSetIntent();
			mAutoOffTimePref.setEnabled(bAutoOffEnabled);
		}
*/
		return true;
	}

	private void showTimePicker(boolean bPowerOn) {
		if(bPowerOn){
			SharedPreferences PowerOntimer = getSharedPreferences("com.android.settings_preferences", Context.MODE_PRIVATE);
			int PowerOnhour_summary=PowerOntimer.getInt("poweron_hour", 0);
			int PowerOnminute_summary=PowerOntimer.getInt("poweron_minute", 0);
			mAutoOnHour=PowerOnhour_summary;
			mAutoOnMinute=PowerOnminute_summary;

			Log.i("poweron_time",mAutoOnHour+","+mAutoOnMinute+"*********");
			
			TimePickerDialog timepicker1 =  new TimePickerDialog(this, 
				
				new TimePickerDialog.OnTimeSetListener() {					
					@Override
					public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

						SharedPreferences PowerOntimer = getSharedPreferences("com.android.settings_preferences", Context.MODE_PRIVATE);
											

   					 	Calendar c = Calendar.getInstance();
   	                                   c.set(Calendar.HOUR_OF_DAY, hourOfDay);
   	                                   c.set(Calendar.MINUTE, minute);                                 	 
   				              //mAutoOnTimePref.setSummary(formatTime(mAutoOnHour,mAutoOnMinute));
					       //Settings.System.putInt(mContentResolver, AUTO_ON_HOUR, mAutoOnHour);
						//Settings.System.putInt(mContentResolver, AUTO_ON_MINUTE, mAutoOnMinute);
   	                                poweron_time=c.getTimeInMillis();
   	                                int day=c.get(Calendar.DAY_OF_MONTH);
   	                                int hour=c.get(Calendar.HOUR_OF_DAY);
   	                                int minute_time=c.get(Calendar.MINUTE);
//   	                             SharedPreferences PowerOntimer = PreferenceManager.getDefaultSharedPreferences(this);
   	                             
   	                           editor = PowerOntimer.edit();
   	                       editor.putLong("poweron",poweron_time);
   	                       editor.putInt("poweron_day", day);
   	                       editor.putInt("poweron_hour", hour);
   	                       editor.putInt("poweron_minute", minute_time);
						   editor.putLong("current_time", System.currentTimeMillis());
   	                    editor.commit();
   	                 mwrapper = Wrapper.getWrapperInstance();
   	              
   	              int power_on=(int)Powerontime( PowerOntimer, poweron_time)/60000;
   	       	mwrapper.setWakeupTimer(power_on);
   	       	
   	                                Log.i("poweron_time",poweron_time+"");
   	                             Log.i("PowerOntimer",power_on+"!!!!!!!!!!!");
								 Log.i("poweron_time",hour+","+minute_time+"%%%%%%%%%");
								 mSetPowerOntimer.setSummary(hour+","+minute_time);
						SendAutoOnOffSetIntent();
						
						
												
					}
				}, 
				mAutoOnHour, 
				mAutoOnMinute,
                     	DateFormat.is24HourFormat(this));			
     	              timepicker1.show();    	          
		}else{

			TimePickerDialog timepicker2=  new TimePickerDialog(this, 
				
				new TimePickerDialog.OnTimeSetListener() {					
					@Override
					public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
						mAutoOffHour = hourOfDay;
   				        	mAutoOffMinute = minute;
   					 	Calendar c = Calendar.getInstance();
   	                                   c.set(Calendar.HOUR_OF_DAY, hourOfDay);
   	                                   c.set(Calendar.MINUTE, minute);                                 	 
   				             // mAutoOffTimePref.setSummary(formatTime(mAutoOffHour,mAutoOffMinute));
						//Settings.System.putInt(mContentResolver, AUTO_OFF_HOUR, mAutoOffHour);
						//Settings.System.putInt(mContentResolver, AUTO_OFF_MINUTE, mAutoOffMinute);
						SendAutoOnOffSetIntent();
					}
				}, 
				mAutoOffHour, 
				mAutoOffMinute,
                     	DateFormat.is24HourFormat(this));			
     	              timepicker2.show();
		}
       
    }

	public String formatTime(int hour, int minute)
	 {
		 String strFormat = DateFormat.is24HourFormat(this) ? M24 : M12;
		 Calendar c = Calendar.getInstance();
		 Date newDate = new Date();
		 newDate.setHours(hour);
		 newDate.setMinutes(minute);
		 c.setTime(newDate);
		 String strShowTime = (String)DateFormat.format(strFormat, c);
		 return strShowTime;
	 }

  public void SendAutoOnOffSetIntent(){
  	/*
		Intent intent = new Intent("com.android.deskclock.AUTO_POWER_ON_OFF");
		mActivity.sendBroadcast(intent);	
*/
  }
  
  public long getPoweronTime()
  {
	  return poweron_time;
  }
  
  public long Powerontime(SharedPreferences mSetPowerOntimer, long poweronTime){
	 // SharedPreferences mSetPowerOntimer = PreferenceManager.getDefaultSharedPreferences(this);
//	  SharedPreferences PowerOntimer = PreferenceManager.getDefaultSharedPreferences(this);
	  //mSetPowerOntimer = getSharedPreferences("com.google.tv.settings_preferences", Context.MODE_PRIVATE);
	  poweronTime=mSetPowerOntimer.getLong("poweron",poweron_time);
	  
	  Boolean use_on_time=mSetPowerOntimer.getBoolean("use_on_time",false);
	  Boolean once=mSetPowerOntimer.getBoolean("once",false);
		Boolean week_monday=mSetPowerOntimer.getBoolean("week_monday",false);
		Boolean week_tuesday=mSetPowerOntimer.getBoolean("week_tuesday",false);			
		Boolean week_wednesday=mSetPowerOntimer.getBoolean("week_wednesday",false);
		Boolean week_thursday=mSetPowerOntimer.getBoolean("week_thursday",false);
		Boolean week_friday=mSetPowerOntimer.getBoolean("week_friday",false);
		Boolean week_saturday=mSetPowerOntimer.getBoolean("week_saturday",false);
		Boolean week_sunday=mSetPowerOntimer.getBoolean("week_sunday",false);		
					
		Calendar c = Calendar.getInstance();
		int today = c.get(Calendar.DAY_OF_WEEK); // get current day in a week
		Log.i("today",today+"");
			
		currenttime = mSetPowerOntimer.getLong("current_time",System.currentTimeMillis());//get current time
		Log.i("currenttime",currenttime+"");
		if(use_on_time==true)
		{
//			time=poweroff_time-currenttime;
//			Log.i("time1",time+"");
//		}
//		else
//		{
			


			if(once==true)
			{
				time=poweronTime-currenttime;	
				Log.i("time2",time+"");
			}
			else
			{
			
				if(week_monday==true)
				{
					setontime[0]=poweronTime-currenttime+(1-today+1+7)%7*24*60*60*1000;
					Log.i("settime[0]",setontime[0]+"");
				}else
				{
					setontime[0]=0;
				}
				if(week_tuesday==true)
				{
					setontime[1]=poweronTime-currenttime+(2-today+1+7)%7*24*60*60*1000;
					Log.i("settime[1]",setontime[1]+"");
				}else
				{
					setontime[1]=0;
				}
				if(week_wednesday==true)
				{
					setontime[2]=poweronTime-currenttime+(3-today+1+7)%7*24*60*60*1000;
					Log.i("settime[2]",setontime[2]+"");
				}else
				{
					setontime[2]=0;
				}
				if(week_thursday==true)
				{
					setontime[3]=poweronTime-currenttime+(4-today+1+7)%7*24*60*60*1000;
					Log.i("settime[3]",setontime[3]+"");
				}else
				{
					setontime[3]=0;
				}
				if(week_friday==true)
				{
					setontime[4]=poweronTime-currenttime+(5-today+1+7)%7*24*60*60*1000;
					Log.i("settime[4]",setontime[4]+"");
				}else
				{
					setontime[4]=0;
				}
				if(week_saturday==true)
				{
					setontime[5]=poweronTime-currenttime+(6-today+1+7)%7*24*60*60*1000;
					Log.i("settime[5]",setontime[5]+"");
				}else
				{
					setontime[5]=0;
				}
				if(week_sunday==true)
				{
					setontime[6]=poweronTime-currenttime+(7-today+1+7)%7*24*60*60*1000;
					Log.i("settime[6]",setontime[6]+"");
				}else
				{
					setontime[6]=0;
				}
				if(once==false&&week_monday==false&&week_tuesday==false&&week_wednesday==false&&week_thursday==false
							&&week_friday==false&&week_saturday==false&&week_sunday==false)
								{
									setontime[7]=poweronTime-currenttime; 
									Log.i("setontime[7]",setontime[7]+"");
								}
				else
				{
					setontime[7]=0;
				}
				//for list, sort by time
	        	for(int i=0;i<setontime.length;i++){
	        		Log.i("i","!!!!!!!!!!"+i);	        		
	        		for(int j=i+1;j<setontime.length;j++)
	        		{
	        			if(setontime[i]>setontime[j]){
	        				long temp=setontime[i];
	        				setontime[i]=setontime[j];
	        				setontime[j]=temp;			        				
	        			}        					
	        		}
	        		Log.i("settime","....@"+setontime[i]);
	        	}
	        	
	        	for(int k=0;k<setontime.length;k++)
	        	{
	        		Log.i("time","%%%%%%"+k);
	        		Log.i("time","--..#"+setontime[k]);
	        		Log.i("time","@@@@@@@@@@@@@"+setontime.length);
	        		
	        		if(setontime[k]>0)
	        			{
	        			Log.i("time","$$$$$$$$$$$$$$"+setontime[k]);
	        			time=setontime[k];
	        		Log.i("time3",time+"");
	        		break;
	        		}			        		
	        	}														        	
			}											
		}
		Log.i("time",time+"");
		return time;
		
  }

}

